<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    showFooter
    :title="getTitle"
    width="600px"
    @ok="handleSubmit"
  >
    <div class="upload-container">
      <div class="button-group">
        <vxe-button status="primary" @click="selectEvent1">
          <template #default>
            <UploadOutlined style="margin-right: 5px" />
            上传文件
          </template>
        </vxe-button>
        <vxe-button @click="downloadEvent">
          <template #default>
            <DownloadOutlined style="margin-right: 5px" />
            下载模板
          </template>
        </vxe-button>
      </div>

      <div v-if="state.file" class="file-info">
        <div class="file-card">
          <FileOutlined style="font-size: 24px; color: #1890ff; margin-right: 10px" />
          <div class="file-details">
            <div class="file-name">{{ state.file.name }}</div>
            <div class="file-size">{{ formatFileSize(state.file.size) }}</div>
          </div>
          <CloseOutlined
            class="remove-btn"
            @click="state.file = null"
            title="移除文件"
          />
        </div>
      </div>

      <div v-else class="upload-hint">
        <InboxOutlined style="font-size: 48px; color: #1890ff; margin-bottom: 10px" />
        <p>请点击"上传文件"按钮选择Excel文件</p>
      </div>
      <div class="upload-tips">
        <ul>
          <li>仅支持.xlsx格式的Excel文件</li>
          <li>文件大小不能超过10MB</li>
          <li>请确保文件格式与模板一致</li>
        </ul>
      </div>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
import { VXETable } from 'vxe-table'
import {ref, computed, unref, reactive} from 'vue';
import { BasicModal, useModalInner } from '@gui-pkg/antdcomponents';
import { message } from "ant-design-vue";
import {
  UploadOutlined,
  DownloadOutlined,
  FileOutlined,
  InboxOutlined,
  CloseOutlined
} from '@ant-design/icons-vue';
import { useUserStoreWithOut } from '@/store/modules/user';
import { bacthImportData } from '@/api/alerts/warningConfig';
import axios from 'axios';

const isUpdate = ref(true);
const rowId = ref('');
const userStore = useUserStoreWithOut();
const emit = defineEmits(['success', 'register']);
const loading = ref(false);

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetModalState();
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    rowId.value = data.record.id;
  }
});

const state = reactive({
  file: null as File | null,
});

const PUBLIC_PATH:string = import.meta.env.VITE_PUBLIC_PATH_ALL;

// 重置模态框状态
const resetModalState = () => {
  state.file = null;
};

// 格式化文件大小显示
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

const downloadEvent = () => {
  // 请求文件
  fetch(`${PUBLIC_PATH}/data/template.xlsx`)
    .then(response => response.blob())
    .then(blob => {
      // 下载到本地
      VXETable.saveFile({ filename: 'template', type: 'xlsx', content: blob })
      message.success('模板下载成功');
    })
    .catch(() => {
      message.error('模板下载失败');
    });
};

const selectEvent1 = async () => {
  try {
    const { file } = await VXETable.readFile({
      types: ['xlsx'],
      message: '请选择.xlsx格式的文件'
    });

    // 检查文件类型
    if (!file.name.endsWith('.xlsx')) {
      message.error('仅支持.xlsx格式的文件');
      return;
    }

    // 检查文件大小（限制10MB）
    if (file.size > 10 * 1024 * 1024) {
      message.error('文件大小不能超过10MB');
      return;
    }

    state.file = file;
    // message.success(`已选择文件: ${file.name}`);
  } catch (e) {
    // 用户取消选择文件时不提示错误
    if (e !== 'cancel') {
      message.error('文件选择失败');
    }
  }
};

const getTitle = computed(() => (!unref(isUpdate) ? '批量导入' : '编辑数据'));

async function handleSubmit() {
  // 检查是否已选择文件
  if (!state.file) {
    message.error('请先选择要上传的文件');
    return;
  }

  try {
    setModalProps({ confirmLoading: true });
    loading.value = true;

    // 创建FormData对象，用于文件上传
    const formData = new FormData();
    formData.append('file', state.file);

    // 可以添加其他参数
    formData.append('uploader', userStore.getUserInfo?.username || 'unknown');
    formData.append('uploadTime', new Date().toISOString());

    // 调用API上传文件
    await bacthImportData(formData);

    message.success('文件上传成功');
    closeModal();
    emit('success');
  } catch (error: any) {
    console.error('Upload error:', error);
    message.error(error.message || '文件上传失败，请重试');
  } finally {
    setModalProps({ confirmLoading: false });
    loading.value = false;
  }
}


</script>

<style lang="less" scoped>
.upload-container {
  padding: 10px 0;

  .button-group {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
  }

  .file-info {
    margin: 15px 0;

    .file-card {
      display: flex;
      align-items: center;
      padding: 12px;
      border: 1px solid #d9d9d9;
      border-radius: 6px;
      background-color: #fafafa;

      .file-details {
        flex: 1;

        .file-name {
          font-weight: 500;
          margin-bottom: 4px;
        }

        .file-size {
          color: #999;
          font-size: 12px;
        }
      }

      .remove-btn {
        color: #999;
        cursor: pointer;
        padding: 5px;

        &:hover {
          color: #ff4d4f;
        }
      }
    }
  }

  .upload-hint {
    text-align: center;
    padding: 10px 0;
    color: #999;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    margin: 15px 0;
    background-color: #fafafa;
  }

  .upload-tips {
    margin-top: 20px;
    padding: 15px;
    background-color: #f6f8ff;
    border-radius: 6px;
    border-left: 3px solid #1890ff;

    h4 {
      margin-top: 0;
      margin-bottom: 10px;
      color: #1890ff;
    }

    ul {
      margin-bottom: 0;
      padding-left: 16px;

      li {
        color: #666;
        line-height: 1.8;
      }
    }
  }
}
</style>
